import React from 'react';
import { Button, notification, message } from 'antd';
import { LOGIN_ROUTE_PATH } from "@/models/constant";
import { history } from "@umijs/max";

//
export const MessageError = (error: any) =>{
  // message.error(`${error.info.code}  ${error.info.message}  data: ${error.info.data}`);
  message.error(JSON.stringify(error));

  // if(error.info.code == ErrorCode.NOT_LOGIN_401) {
  //   ToLogin();
  // }
}


//
export const ToLogin = () => {
  const curPath = window.location.pathname;
  history.push(`${LOGIN_ROUTE_PATH}?redirect=${encodeURIComponent(curPath)}`);
};


//

const key = 'codeNotification';
export const showNotification = (code: string) => {
  notification.open({
    key,
    placement: 'top',
    duration: 0,  // 不自动关闭
    message: '',
    description: (
      <div>
        <span>验证码: {code}</span>
        <Button
          type="default"
          size="small"
          onClick={() => {
            copyToClipboard(code)
            notification.destroy(key)
          }}
          style={{ marginLeft: 10 }}
        >
          复制
        </Button>
      </div>
    ),
    style: {
      padding: '10px 15px',           // 修改内边距，减少通知的大小
      maxWidth: '300px',              // 设置最大宽度，避免通知太大
    },
    
  });
};

const copyToClipboard = (text: string) => {
  if (navigator.clipboard) {
    // 使用 Clipboard API 复制
    navigator.clipboard.writeText(text).then(() => {
      message.success('验证码已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  } else {
    // 兼容老版本浏览器
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    message.success('验证码已复制到剪贴板');
  }
};



// scrollToTop
export const scrollToTop = () => {
  let sTop = document.documentElement.scrollTop || document.body.scrollTop
  if (sTop > 0) {
      window.requestAnimationFrame(scrollToTop)
      window.scrollTo(0, 0)
  }
};
